<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="500px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="user-form"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户名"
          clearable
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          :placeholder="isEdit ? '留空则不修改密码' : '请输入密码'"
          clearable
          show-password
        />
        <div v-if="isEdit" class="form-tip">
          <el-text type="info" size="small">留空则不修改当前密码</el-text>
        </div>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
          clearable
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createUser, updateUser } from '@/api/user'
import CryptoJS from 'crypto-js'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  username: '',
  password: '',
  remark: ''
})

// 表单验证规则
const rules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: props.isEdit ? [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ] : [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 200, message: '备注不能超过200个字符', trigger: 'blur' }
  ]
}))

// MD5加密函数
const md5Encrypt = (text) => {
  return CryptoJS.MD5(text).toString().toUpperCase()
}

// 监听visible变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal && props.isEdit && props.userData) {
    // 编辑模式，填充数据
    nextTick(() => {
      Object.assign(form, {
        username: props.userData.username || '',
        password: '',
        remark: props.userData.remark || ''
      })
    })
  } else if (newVal && !props.isEdit) {
    // 新增模式，重置表单
    resetForm()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    username: '',
    password: '',
    remark: ''
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    if (props.isEdit) {
      // 编辑用户
      const submitData = {
        param: {
          id: props.userData.id,
          username: form.username,
          remark: form.remark || ''
        }
      }

      // 如果输入了密码，则加密后传递
      if (form.password && form.password.trim()) {
        submitData.param.password = md5Encrypt(form.password)
      } else {
        // 不修改密码时，传递空字符串或不传递密码字段
        submitData.param.password = ''
      }

      await updateUser(submitData)
      ElMessage.success('用户更新成功')
      
      // 关闭对话框并通知父组件刷新列表
      handleClose()
      emit('success')
    } else {
      // 新增用户
      const submitData = {
        param: {
          username: form.username,
          password: md5Encrypt(form.password), // MD5加密密码
          remark: form.remark || ''
        }
      }

      await createUser(submitData)
      ElMessage.success('用户创建成功')
      
      // 关闭对话框并通知父组件刷新列表
      handleClose()
      emit('success')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.user-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-textarea {
  resize: vertical;
}

/* 表单项标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: box-shadow 0.2s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 文本域样式 */
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: box-shadow 0.2s ease;
}

:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-textarea.is-focus .el-textarea__inner) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 表单提示样式 */
.form-tip {
  margin-top: 4px;
  line-height: 1.4;
}
</style>
